package com.hrt.datasender.datacollect.drive.modbus.rtu;

import java.util.HashMap;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.hrt.datasender.datacollect.drive.DriveConfigModel;
import com.hrt.datasender.datacollect.drive.DriveTimer;
import com.hrt.datasender.datadao.model.BcDevicesModel;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.SerialModel;
import com.hrt.serial.modbus.ModbusRequestModel;

/**
 * modbus数据询问器
 * 
 * @author gislin
 *
 */
public class ModbusSerialDataAsker extends DriveTimer {

    private ILog log = null;

    private SerialModel askModel = null;

    @Override
    public void executeTimer(DriveConfigModel configs, BcDevicesModel deviceData) {

        try {
            log = MyLog.getInstance().getLogger(getClass().getName() + "." + deviceData.getDeviceName());
            askData(deviceData, configs);
            log.info("询问"+ askModel.toString());
        }
        catch (Exception e) {
            log.error("执行定时任务出错", e);
        }

    }

    private void askData(BcDevicesModel device, DriveConfigModel deviceConfigs) {

        SerialModel askModel = getAskDataModel(device, deviceConfigs);
        MqKit.productAskDataMsgToSerialMQ(askModel);
    }

    /**
     * 获取modbus串口询问报文对象
     * 
     * @param device
     * @param deviceConfigs
     * @return
     */
    private SerialModel getAskDataModel(BcDevicesModel device, DriveConfigModel deviceConfigs) {

        if (askModel == null) {
            HashMap<String, String> configs = deviceConfigs.getConfig();

            String slaveNo = configs.get("slaveNo");
            String startNoStr = configs.get("startNo");
            String dataLengthStr = configs.get("dataLength");
            String fuctionCodeStr = configs.get("functionCode");

            int startNo = Integer.parseInt(startNoStr);
            int dataLength = Integer.parseInt(dataLengthStr);
            int functionCode = Integer.parseInt(fuctionCodeStr);

            ModbusRequestModel model = new ModbusRequestModel();
            model.setMn(slaveNo);
            model.setDataLength(dataLength);
            model.setStartAddr(startNo);
            model.setFunctionCode(functionCode);

            askModel = new SerialModel(model.getSendByte(), device.getComNum(), slaveNo);
        }

        return askModel;
    }
}
